package com.nacol.demo.contract.registry;

import cn.hutool.core.util.StrUtil;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.serviceregistry.Registration;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;

import java.util.Arrays;
import java.util.Map;
import java.util.Optional;

import static com.nacol.demo.contract.registry.CustomMetaData.*;

/**
 * @Author Nacol(姚秋实)
 * @Date 2023/12/13
 * @Title 服务注册切面
 * @Description 1.获取启动参数中自定义metadata配置; 2.给metadata赋值。
 */

@Slf4j
@Aspect
@Component
public class ServiceRegisterAspect {

    @Autowired
    Environment environment;

    @Before("execution(* org.springframework.cloud.client.serviceregistry.ServiceRegistry.register(..))")
    public void beforeRegister(JoinPoint joinPoint) {
        Object[] args = joinPoint.getArgs();

        // STEP 获取注册配置
        Optional<Object> registrationOpt = Arrays.stream(args).filter(arg -> arg instanceof Registration).findFirst();
        if (registrationOpt.isEmpty()) {
            log.error("Modify metadata：registration not found.");
            return;
        }
        Registration registration = (Registration) registrationOpt.get();

        // STEP 获取默认【metadata】
        Map<String, String> metadata = registration.getMetadata();

        // STEP 设置自定义【metadata】
        updateMetadataIfPresent(metadata, REGISTRY_TYPE.field, REGISTRY_TYPE.startupParameter);
        updateMetadataIfPresent(metadata, REGISTRY_DC.field, REGISTRY_DC.startupParameter);
        updateMetadataIfPresent(metadata, REGISTRY_ZONE.field, REGISTRY_ZONE.startupParameter);
    }

    /**
     * @Author Nacol(姚秋实)
     * @Date 2023/12/13
     * @Title 通过启动配置更新metadata
     */
    private void updateMetadataIfPresent(Map<String, String> metadata, String field, String startupParameter) {
        String value = environment.getProperty(startupParameter);
        if (StrUtil.isNotBlank(value)) {
            metadata.put(field, value);
        }
    }

}
